<template>
  <el-container style="height: 100vh;">
    <!-- 左侧边栏 -->
    <el-aside width="200px" style="background-color: #f0f9ff; border-right: 1px solid #e6e6e6;">
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical"
          background-color="#f0f9ff"
          text-color="#333"
          active-text-color="#409EFF"
          router
      >
        <el-menu-item index="/">
          <el-icon><House /></el-icon>
          <span>主界面</span>
        </el-menu-item>

        <!-- 系统监控 -->
        <el-sub-menu index="1">
          <template #title>
            <el-icon><Monitor /></el-icon>
            <span>系统监控</span>
          </template>
          <el-menu-item index="/node-status">节点状态</el-menu-item>
          <el-menu-item index="/live-view">实时画面</el-menu-item>
          <el-menu-item index="/data-collection">数据收集</el-menu-item>
        </el-sub-menu>
        <!-- 学生管理 -->
        <el-sub-menu index="4">
          <template #title>
            <el-icon><User /></el-icon>
            <span>学生管理</span>
          </template>
          <el-menu-item index="/student-info">学生基本信息</el-menu-item>
          <el-menu-item index="/group-emotion">群体情绪状态</el-menu-item>
        </el-sub-menu>
        <!-- 人脸界面 -->
        <el-sub-menu index="2">
          <template #title>
            <el-icon><User /></el-icon>
            <span>人脸界面</span>
          </template>
          <el-menu-item index="/face-upload">人脸图片上传</el-menu-item>
          <el-menu-item index="/face-records">人脸数据记录</el-menu-item>
        </el-sub-menu>

        <!-- 心理健康管理 -->
        <el-sub-menu index="3">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>心理健康管理</span>
          </template>
          <el-menu-item index="/psychological-test">学生心理测评表</el-menu-item>
          <el-menu-item index="/abnormal-manage">异常人员管理</el-menu-item>
          <el-menu-item index="/questionnaire">心理问卷和结果</el-menu-item>
        </el-sub-menu>

        <el-menu-item index="/basic-info">
          <el-icon><InfoFilled /></el-icon>
          <span>基础信息</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container>
      <!-- 顶部导航栏 -->
      <el-header style="background-color: #f0f9ff; border-bottom: 1px solid #e6e6e6; display: flex; align-items: center;">
        <div style="flex-grow: 1;">
          <h2 style="color: #409EFF; margin: 0;">山西工学院心理健康检测与预测系统</h2>
        </div>
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-avatar :size="40" :src="avatarUrl" />
            <el-icon style="margin-left: 5px;"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>个人中心</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <!-- 主内容区 -->
      <el-main style="background-color: #f5f7fa; padding: 20px;">
        <!-- 使用 router-view 显示其他路由 -->
        <router-view v-if="$route.path !== '/'"></router-view>

        <!-- 首页内容 -->
        <template v-if="$route.path === '/'">
          <!-- 第一行：顶部四个小卡片 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">学生总统计</div>
                <div class="stat-value">1,245</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">问题学生</div>
                <div class="stat-value">32</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">问卷完成度</div>
                <div class="stat-value">87%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-title">摄像头异常</div>
                <div class="stat-value" :style="{color: cameraStatus.abnormal > 0 ? '#F56C6C' : '#67C23A'}">
                  {{ cameraStatus.abnormal }}个
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 第二行：情绪状态扇形图和问题学生数量折射图 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <!-- 情绪状态扇形图 -->
            <el-col :span="12">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>情绪状态扇形图</span>
                  </div>
                </template>
                <div style="height: 250px;" ref="emotionChartRef"></div>
              </el-card>
            </el-col>

            <!-- 问题学生数量折射图 -->
            <el-col :span="12">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>问题学生数量折射图</span>
                  </div>
                </template>
                <div style="height: 250px;" ref="problemStudentChartRef"></div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 第三行：合并的时间线卡片 -->
          <el-row>
            <el-col :span="24">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>系统事件时间线</span>
                  </div>
                </template>
                <el-timeline>
                  <!-- 合并所有事件并按时间排序 -->
                  <el-timeline-item
                      v-for="(event, index) in sortedEvents"
                      :key="index"
                      :timestamp="event.time"
                      :color="getEventColor(event)"
                      placement="top"
                  >
                    <el-tag :type="getEventTagType(event)">
                      {{ getEventType(event) }}: {{ event.camera || event.student }}
                      {{ getEventStatus(event) }}
                    </el-tag>
                    <p>{{ event.message }}</p>
                  </el-timeline-item>
                </el-timeline>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import {
  House,
  Monitor,
  User,
  Document,
  InfoFilled,
  ArrowDown
} from '@element-plus/icons-vue'

const route = useRoute()
const avatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const emotionChartRef = ref(null)
const problemStudentChartRef = ref(null)

const activeMenu = computed(() => {
  return route.path
})

// 摄像头状态数据
const cameras = ref([
  { name: '教室前摄像头', status: 'normal' },
  { name: '教室后摄像头', status: 'normal' },
  { name: '走廊摄像头', status: 'abnormal' },
  { name: '实验室摄像头', status: 'normal' }
])

const cameraStatus = computed(() => {
  const total = cameras.value.length
  const abnormal = cameras.value.filter(c => c.status === 'abnormal').length
  return {
    total,
    normal: total - abnormal,
    abnormal
  }
})

// 情绪状态数据
const emotionData = ref({
  happy: 45,
  normal: 30,
  sad: 15,
  angry: 7,
  fear: 3
})

// 问题学生数据
const problemStudentData = ref([
  { date: '周一', count: 5 },
  { date: '周二', count: 8 },
  { date: '周三', count: 12 },
  { date: '周四', count: 10 },
  { date: '周五', count: 7 },
  { date: '周六', count: 3 },
  { date: '周日', count: 2 }
])

// 时间线事件数据
const cameraEvents = ref([
  {
    time: '2023-05-01 09:30',
    camera: '走廊摄像头',
    status: 'abnormal',
    message: '画面丢失，网络连接不稳定',
    type: 'camera'
  },
  {
    time: '2023-05-01 10:15',
    camera: '教室后摄像头',
    status: 'abnormal',
    message: '画面模糊，需要清洁镜头',
    type: 'camera'
  },
  {
    time: '2023-05-01 11:20',
    camera: '教室后摄像头',
    status: 'normal',
    message: '镜头清洁完成，恢复正常',
    type: 'camera'
  }
])

const emotionEvents = ref([
  {
    time: '2023-05-01 08:45',
    student: '张三',
    level: 'high',
    message: '检测到持续低落情绪，建议关注',
    type: 'emotion'
  },
  {
    time: '2023-05-01 10:30',
    student: '李四',
    level: 'medium',
    message: '情绪波动较大，建议观察',
    type: 'emotion'
  },
  {
    time: '2023-05-01 14:15',
    student: '王五',
    level: 'low',
    message: '情绪恢复正常水平',
    type: 'emotion'
  }
])

const problemStudentEvents = ref([
  {
    time: '2023-05-01 09:10',
    student: '赵六',
    type: 'add',
    message: '检测到异常行为，已加入关注列表',
    eventType: 'problem'
  },
  {
    time: '2023-05-01 13:25',
    student: '钱七',
    type: 'remove',
    message: '经过辅导，已从问题学生列表移除',
    eventType: 'problem'
  }
])

// 合并并排序所有事件
const sortedEvents = computed(() => {
  const allEvents = [
    ...cameraEvents.value,
    ...emotionEvents.value,
    ...problemStudentEvents.value
  ]
  return allEvents.sort((a, b) => new Date(a.time) - new Date(b.time))
})

// 获取事件颜色
const getEventColor = (event) => {
  if (event.type === 'camera') {
    return event.status === 'normal' ? '#67C23A' : '#F56C6C'
  } else if (event.type === 'emotion') {
    return event.level === 'high' ? '#F56C6C' : event.level === 'medium' ? '#E6A23C' : '#67C23A'
  } else {
    return event.type === 'add' ? '#F56C6C' : '#67C23A'
  }
}

// 获取事件标签类型
const getEventTagType = (event) => {
  if (event.type === 'camera') {
    return event.status === 'normal' ? 'success' : 'danger'
  } else if (event.type === 'emotion') {
    return event.level === 'high' ? 'danger' : event.level === 'medium' ? 'warning' : 'success'
  } else {
    return event.type === 'add' ? 'danger' : 'success'
  }
}

// 获取事件类型文本
const getEventType = (event) => {
  if (event.type === 'camera') return '摄像头'
  if (event.type === 'emotion') return '情绪'
  return '问题学生'
}

// 获取事件状态文本
const getEventStatus = (event) => {
  if (event.type === 'camera') {
    return event.status === 'normal' ? '恢复正常' : '发生异常'
  } else if (event.type === 'emotion') {
    return event.level === 'high' ? '高风险' : event.level === 'medium' ? '中风险' : '低风险'
  } else {
    return event.type === 'add' ? '新增' : '解除'
  }
}

// 初始化图表
const initCharts = () => {
  if (!emotionChartRef.value || !problemStudentChartRef.value) return

  // 情绪状态扇形图
  const emotionChart = echarts.init(emotionChartRef.value)
  const emotionOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['快乐', '正常', '悲伤', '愤怒', '恐惧']
    },
    series: [
      {
        name: '情绪状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: emotionData.value.happy, name: '快乐', itemStyle: { color: '#67C23A' } },
          { value: emotionData.value.normal, name: '正常', itemStyle: { color: '#409EFF' } },
          { value: emotionData.value.sad, name: '悲伤', itemStyle: { color: '#E6A23C' } },
          { value: emotionData.value.angry, name: '愤怒', itemStyle: { color: '#F56C6C' } },
          { value: emotionData.value.fear, name: '恐惧', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  emotionChart.setOption(emotionOption)

  // 问题学生数量折射图
  const problemStudentChart = echarts.init(problemStudentChartRef.value)
  const problemStudentOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: problemStudentData.value.map(item => item.date),
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '问题学生数量',
        type: 'bar',
        barWidth: '60%',
        data: problemStudentData.value.map(item => ({
          value: item.count,
          itemStyle: {
            color: item.count > 10 ? '#F56C6C' : item.count > 5 ? '#E6A23C' : '#67C23A'
          }
        })),
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: function(params) {
            const count = problemStudentData.value[params.dataIndex].count
            return count > 10 ? '#F56C6C' : count > 5 ? '#E6A23C' : '#67C23A'
          }
        }
      }
    ]
  }
  problemStudentChart.setOption(problemStudentOption)

  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', function() {
    emotionChart.resize()
    problemStudentChart.resize()
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })

  // 解决 ResizeObserver 报错问题
  const originalErrorHandler = window.onerror
  window.onerror = (message, source, lineno, colno, error) => {
    if (typeof message === 'string' && message.includes('ResizeObserver')) {
      return true // 阻止默认错误处理
    }
    if (originalErrorHandler) {
      return originalErrorHandler(message, source, lineno, colno, error)
    }
    return false
  }

  window.addEventListener('error', (event) => {
    if (event.message && event.message.includes('ResizeObserver')) {
      event.preventDefault()
    }
  })
})
</script>

<style scoped>
.el-menu-vertical {
  border-right: none;
}
.el-header {
  padding: 0 20px;
}
.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.camera-status-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.camera-status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}
.camera-info {
  display: flex;
  align-items: center;
}
.stat-card {
  text-align: center;
  padding: 15px 0;
}
.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
</style>